package com.seqb.system.shiro;

import com.seqb.common.config.SpringConfig;
import com.seqb.common.utils.ShiroUtils;
import com.seqb.manage.menu.service.MenuService;
import com.seqb.manage.user.dao.UserDao;
import com.seqb.manage.user.domain.UserDO;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/26
 */
public class UserRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        Long userId = ShiroUtils.getUserId();
        MenuService menuService = SpringConfig.getBean(MenuService.class);
        Set<String> perms = menuService.listPerms(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Map<String, Object> map = new HashMap<>(16);
        map.put("account", username);
        String password = new String((char[]) token.getCredentials());
        UserDao userMapper = SpringConfig.getBean(UserDao.class);
        // 查询账号信息
        List<UserDO> list = userMapper.selectByMap(map);
        if (null == list || list.size() <= 0) {
            throw new UnknownAccountException("账号不存在，请重新输入！");
        }
        UserDO user = list.get(0);
        // 账号密码错误
        if (!password.equals(user.getPassword())) {
            throw new IncorrectCredentialsException("密码不正确，请重新输入！");
        }
        // 账号锁定
        if ("0".equals(user.getState())) {
            throw new LockedAccountException("账号已被锁定，请联系管理员！");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }

}
